import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
import User from "../views/User.vue";
import UserProfile from "../views/user/UserProfile.vue";
import AccountInfo from "../views/user/AccountInfo.vue";
import SecuritySettings from "../views/user/SecuritySettings.vue";
import Withdraw from "../views/user/Withdraw.vue";
import PaymentSettings from "../views/user/PaymentSettings.vue";
import WithdrawList from "../views/user/WithdrawList.vue";
import Team from "../views/user/Team.vue";
import ConsumptionList from "../views/user/ConsumptionList.vue";

Vue.use(VueRouter);

const routes = [
  // 认证相关路由 - 无布局
  {
    path: "/auth",
    component: () =>
      import("@/layouts/AuthLayout.vue").catch((error) => {
        console.error("Failed to load AuthLayout:", error);
      }),
    children: [
      {
        path: "",
        redirect: "login",
      },
      {
        path: "login",
        name: "Login",
        component: () =>
          import("@/views/auth/Login.vue").catch((error) => {
            console.error("Failed to load Login:", error);
          }),
      },
      {
        path: "register",
        name: "Register",
        component: () =>
          import("@/views/auth/Register.vue").catch((error) => {
            console.error("Failed to load Register:", error);
          }),
      },
      {
        path: "forgot-password",
        name: "ForgotPassword",
        component: () =>
          import("@/views/auth/ForgotPassword.vue").catch((error) => {
            console.error("Failed to load ForgotPassword:", error);
          }),
      },
    ],
  },

  // 主应用路由 - 使用主布局
  {
    path: "/",
    component: () =>
      import("@/layouts/MainLayout.vue").catch((error) => {
        console.error("Failed to load MainLayout:", error);
      }),
    children: [
      {
        path: "",
        redirect: "/store",
      },
      {
        path: "store",
        name: "AppStore",
        component: () =>
          import("@/views/AppStore.vue").catch((error) => {
            console.error("Failed to load AppStore:", error);
          }),
      },
      {
        path: "chat",
        name: "Chat",
        component: () =>
          import("@/views/Chat.vue").catch((error) => {
            console.error("Failed to load Chat:", error);
          }),
        meta: { requiresAuth: true },
      },
      {
        path: "user",
        name: "User",
        component: User,
      },
      {
        path: "workbench",
        name: "Workbench",
        component: () =>
          import("@/views/Workbench.vue").catch((error) => {
            console.error("Failed to load Workbench:", error);
          }),
      },
    ],
  },

  // 用户中心相关页面 - 使用用户中心布局
  {
    path: "/user-center",
    component: () =>
      import("@/layouts/UserCenterLayout.vue").catch((error) => {
        console.error("Failed to load UserCenterLayout:", error);
      }),
    children: [
      {
        path: "profile",
        name: "UserProfile",
        component: UserProfile,
      },
      {
        path: "account",
        name: "AccountInfo",
        component: AccountInfo,
      },
      {
        path: "security",
        name: "SecuritySettings",
        component: SecuritySettings,
      },
      {
        path: "withdraw",
        name: "Withdraw",
        component: Withdraw,
      },
      {
        path: "payment-settings",
        name: "PaymentSettings",
        component: PaymentSettings,
      },
      {
        path: "withdraw-history",
        name: "WithdrawList",
        component: WithdrawList,
      },
      {
        path: "team",
        name: "Team",
        component: Team,
      },
      {
        path: "consumption",
        name: "ConsumptionList",
        component: ConsumptionList,
      },
      {
        path: "distributor-apply",
        name: "DistributorApply",
        component: () =>
          import("../views/user/DistributorApply.vue").catch((error) => {
            console.error("Failed to load DistributorApply:", error);
          }),
      },
    ],
  },

  // 应用详情页 - 使用用户中心布局
  {
    path: "/app",
    component: () =>
      import("@/layouts/UserCenterLayout.vue").catch((error) => {
        console.error("Failed to load UserCenterLayout:", error);
      }),
    children: [
      {
        path: "detail",
        name: "AppDetail",
        component: () =>
          import("@/views/AppDetail.vue").catch((error) => {
            console.error("Failed to load AppDetail:", error);
          }),
      },
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 路由前置守卫，在路由跳转前进行权限检查和处理
router.beforeEach((to, from, next) => {
  console.log("BeforeEach: to", to.path, "from", from.path);
  // 从 store 中获取用户是否已登录的状态
  const isAuthenticated = store.getters["user/isLoggedIn"];

  // 定义一个函数来处理已登录用户访问登录相关页面的情况
  const handleAuthenticatedUserOnAuthPage = () => {
    // 新增判断：如果是退出登录后跳转，不进行重定向
    if (to.path === "/auth/login" && from.name === "Logout") {
      return null;
    }
    if (to.path.startsWith("/auth/") && isAuthenticated) {
      console.log("Redirecting authenticated user from auth page to home");
      return "/";
    }
    return null;
  };

  // 定义一个函数来处理需要登录权限的页面
  const handleAuthRequiredPage = () => {
    if (to.matched.some((record) => record.meta.requiresAuth)) {
      if (!isAuthenticated) {
        console.log("Redirecting unauthenticated user to login page");
        return {
          path: "/auth/login",
          query: { redirect: to.fullPath },
        };
      }
    }
    return null;
  };

  // 定义一个函数来处理根据路由路径设置对应的 tab
  const handleTabSetting = () => {
    const pathToTab = {
      "/chat": "chat",
      "/store": "appStore",
    };
    const tab = pathToTab[to.path];
    if (tab) {
      // 如果存在对应的 tab，提交 mutation 设置当前激活的 tab
      store.commit("tabBar/SET_ACTIVE_TAB", tab);
    }
    console.log("No auth requirements, proceeding to route");
    next();
  };

  // 首先处理已登录用户访问登录相关页面的情况
  const authPageRedirect = handleAuthenticatedUserOnAuthPage();
  if (authPageRedirect) {
    next(authPageRedirect);
    return;

  }

  // 然后处理需要登录权限的页面
  const authRequiredRedirect = handleAuthRequiredPage();
  if (authRequiredRedirect) {
    next(authRequiredRedirect);
    return;
  }
  // 最后处理根据路由路径设置对应的 tab
  next(handleTabSetting());
});

export default router;
